const express = require('express')
const db = require('../sql/db')
const router = express.Router()
const jwt = require('jsonwebtoken')
const multer = require('multer');
const { json } = require('express');
// 上传文件的文件夹，会自动创建
const upload = multer({ dest: 'uploads/' })

const yanzheng = (req, res, next) => {
    const { username, password } = req.body
    console.log(req.body);
    if (!/^[a-zA-z][a-zA-Z0-9_]{0,9}/.test(username)) {
        next('用户名错误')
    } else {
        next()
    }
}

// 用户登录
router.post('/user/login', (req, res) => {
    const { username, password } = req.body
    db(`select * from users where username = '${username}' and password = '${password}'`, function (err, data) {
        if (err || data.length == 0) return res.send({ code: 400, msg: '用户名或密码错误' })
        // 加密
        // 需要加上Bearer并且加上空隔
        const token = jwt.sign({ username, password, id: data[0].id }, 'user', { expiresIn: '2h' })
        res.send({ code: 200, msg: '登录成功', token: 'Bearer ' + token, id: data[0].id })
    })
})


// 获取用户信息
router.get('/user/info', yanzheng, (req, res, next) => {
    const { id } = req.user
    db(`select * from users where id=${id}`, function (err, data) {
        if (err) return res.send('获取失败')
        console.log(data);
        res.send({ code: 200, data: { username: data[0].username, userpIC: data[0].userPic } })
    })
})

// 获取用户详情
router.get('/user/detail', yanzheng, (req, res, next) => {
    const { id } = req.user
    db(`select * from users where id=${id}`, function (err, data) {
        if (err) return res.send('获取失败')
        res.send({ code: 200, data })
    })
})



// 编辑用户信息
// upload.single('userPic')将上传的文件储存进文件夹
router.post('/user/edit', upload.single('userPic'), function (req, res) {
    const { id } = req.user
    const { filename } = req.file
    const { username, password, nickname, email } = req.body

    db(`update users set username='${username}',password='${password}',email='${email}',nickname='${nickname}',userPic='${filename}' where id = ${id} `, function (err, data) {
        if (err || data.affectedRows == 0) return res.send({ code: 400, msg: '修改失败' })
        res.send({ code: 200, msg: '修改成功' })
    })
})

module.exports = router